﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using Ionic.Zip;
using Utilities;

namespace MaHoaUngDung
{
    public partial class HomeFrm : DevComponents.DotNetBar.Office2007Form
    {
        List<string> lstCopyFilePath;
        TreeNode curNode;
        DriveInfo[] allDrives = DriveInfo.GetDrives();
        string currentPath = "My Computer";
        DirectoryInfo[] curDir;
        bool isCopy = false;

        public HomeFrm()
        {
            InitializeComponent();
            
            //tạo thông tin ban đầu
            UpdateField();
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
        }

        private void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            if (MessageBox.Show("Hệ thống bị lỗi! bạn có muốn tiếp tục?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
            {
                Cursor = Cursors.Default;
                return;
            }
            else
            {
                Application.Exit();
            }
        }

        private void Init()
        {
            lstCopyFilePath = new List<string>();

            //them node "my computer"
            TreeNode myNode = new TreeNode("My Computer", 0, 0);
            MainTreeView.Nodes.Clear();
            MainTreeView.Nodes.Add(myNode);

            curNode = myNode;

            //wait cursor
            int imageKey = 1;
            int selectKey = 1;

            TreeNodeCollection myTreeNodeCollection = myNode.Nodes;

            foreach (DriveInfo myDriveInfo in allDrives)
            {
                switch (myDriveInfo.DriveType)
                {
                    case DriveType.Fixed:
                        imageKey = 1;
                        selectKey = 1;
                        break;
                    case DriveType.Removable:
                        imageKey = 2;
                        selectKey = 2;
                        break;
                    case DriveType.CDRom:
                        imageKey = 3;
                        selectKey = 3;
                        break;
                }
                TreeNode tmp = new TreeNode(myDriveInfo.RootDirectory.ToString().TrimEnd('\\'), imageKey, selectKey);
                myTreeNodeCollection.Add(tmp);
            }
        }

        private void UpdateField()
        {
            User user = Program.CurrentUser;
            tbTen.Text = user.Name;
            tbEmail.Text = user.Email;
            tbDiaChi.Text = user.Address;
            tbDienThoai.Text = user.Phone;
            dtpNgaySinh.Value = user.Birth;
            //ShowTreeView();
            Init();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                // cập nhật thông tin người dùng
                User user = Program.CurrentUser;
                user.Name = tbTen.Text.Trim();
                user.Birth = dtpNgaySinh.Value;
                user.Address = tbDiaChi.Text.Trim();
                user.Phone = tbDienThoai.Text.Trim();

                MessageBox.Show("Cập nhật thành công!.", Utility.InformTitle);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utility.ExceptionTitle);
            }
        }

        private void btnChangePass_Click(object sender, EventArgs e)
        {
            //gọi form đổi pass
            DoiMatKhauFrm updateForm = new DoiMatKhauFrm();
            updateForm.ShowDialog(this);
        }

        private void btnSignOut_Click(object sender, EventArgs e)
        {
            //cập nhật người dùng hiện tại thành null
            //đóng form này
            //trả lại form sign in
            Program.CurrentUser = null;
            this.Close();
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            //Process.Start(".\\Help\\Report.chm");
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (ofdImportUser.ShowDialog(this) == DialogResult.OK)
            {
                string path = ofdImportUser.FileName;
                XmlSerializer serializer = new XmlSerializer(typeof(User));
                TextReader reader = new StreamReader(path);
                try
                {
                    Program.CurrentUser = (User)serializer.Deserialize(reader);
                    UpdateField();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception");
                }
                finally
                {
                    reader.Close();
                }
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (sfdExportUser.ShowDialog(this) == DialogResult.OK)
            {
                string filePath = sfdExportUser.FileName;
                User user = Program.CurrentUser;
                XmlSerializer serializer = new XmlSerializer(typeof(User));
                TextWriter writer = new StreamWriter(filePath, false);
                try
                {
                    serializer.Serialize(writer, user);
                    MessageBox.Show("Export thành công!", Utility.InformTitle);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Utility.ExceptionTitle);
                }
                finally
                {
                    writer.Close();
                }
            }
        }

        private void MainTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode up_node = e.Node;
            string select_path = string.Empty;
            while (up_node.Parent != null)
            {
                select_path = up_node.Text + "\\" + select_path;
                up_node = up_node.Parent;
            }
            select_path.Replace("My Computer\\", "");

            if (select_path != currentPath)
            {
                if (e.Node.Level >= 1)
                    if (Directory.Exists(select_path))
                    {
                        this.Cursor = Cursors.WaitCursor;

                        DirectoryInfo dirInfo = new DirectoryInfo(select_path);

                        curDir = dirInfo.GetDirectories();
                        ExpandTreeNode(e.Node);

                        currentPath = select_path;
                        curNode = e.Node;

                        ShowDirectories();
                        ShowFiles(select_path);
                        labelStatus.Text = select_path;
                        this.MainTreeView.SelectedNode = curNode;

                        this.Cursor = Cursors.Default;
                    }
                    else if (e.Node.Level == 1)
                        MessageBox.Show("thiết bị chưa sẵn sàng!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        MessageBox.Show("không thể truy cập!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ExpandTreeNode(TreeNode currentNode)
        {
            this.Cursor = Cursors.WaitCursor;

            currentNode.Nodes.Clear();
            TreeNodeCollection myTreeNodeCollection = currentNode.Nodes;

            foreach (DirectoryInfo dirInfo in curDir)
            {
                if (CheckConditionToShow(dirInfo.Attributes))
                    myTreeNodeCollection.Add(dirInfo.Name, dirInfo.Name, 4, 5);
            }
            MainTreeView.Sort();
            currentNode.ExpandAll();

            this.Cursor = Cursors.Default;
        }

        private bool CheckConditionToShow(FileAttributes att)
        {
            if ((att & FileAttributes.System) != 0)
            {
                if (showSystemFilesToolStripMenuItem.Checked)
                {
                    return true;
                }
                else
                    return false;
            }
            else if ((att & FileAttributes.Hidden) != 0)
            {
                if (showHiddenFilesToolStripMenuItem.Checked)
                {
                    return true;
                }
                else
                    return false;
            }
            else
            {
                return true;
            }
        }

        private void ShowDirectories()
        {
            MainListView.Items.Clear();

            foreach (DirectoryInfo dirInfo in curDir)
            {
                if (CheckConditionToShow(dirInfo.Attributes))
                {
                    string[] arr = new string[] { dirInfo.Name, "Folder", dirInfo.CreationTime.ToString("g"), dirInfo.LastWriteTime.ToString("g"), };
                    ListViewItem item = new ListViewItem(arr, 4);
                    MainListView.Items.Add(item);
                }
            }
        }

        private void ShowFiles(string sCurrentPath)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(sCurrentPath);
            foreach (FileInfo fileInfo in dirInfo.GetFiles())
            {
                if (CheckConditionToShow(fileInfo.Attributes))
                {
                    string[] arr = new string[] { fileInfo.Name, formatSize(fileInfo.Length), fileInfo.CreationTime.ToString("g"), fileInfo.LastWriteTime.ToString("g"), };
                    ListViewItem item = new ListViewItem(arr, ChooseImgToView(fileInfo));
                    MainListView.Items.Add(item);
                }
            }

        }

        private string formatSize(long lSize)
        {
            string unit = " Byte(s)";
            float fSize = lSize;
            if (fSize >= 1024) //>=1KB
            {
                fSize /= 1024;
                unit = " KB";
                if (fSize >= 1024) //>=1MB
                {
                    fSize /= 1024;
                    unit = " MB";
                    if (fSize >= 1024) //>=1GB
                    {
                        fSize /= 1024;
                        unit = " GB";
                    }
                }
            }
            return string.Format("{0:0.00}", fSize) + unit;
        }

        private int ChooseImgToView(FileInfo file)
        {
            int index;
            switch (file.Extension)
            {
                case ".doc":
                case ".docx":
                    index = 7;
                    break;
                case ".xls":
                case ".xlsx":
                    index = 8;
                    break;
                case ".ppt":
                case ".pptx":
                    index = 9;
                    break;
                case ".pdf":
                    index = 10;
                    break;
                case ".wma":
                case ".wmv":
                case ".avi":
                case ".mp3":
                case ".mp4":
                    index = 11;
                    break;
                case ".zip":
                case ".rar":
                case ".7z":
                    index = 16;
                    break;
                case ".cs":
                case ".vb":
                case ".cpp":
                    index = 12;
                    break;
                case ".xml":
                    index = 14;
                    break;
                case ".dll":
                    index = 15;
                    break;
                default:
                    index = 6;
                    break;
            }

            return index;
        }

        private void MainTreeView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (MainListView.SelectedItems.Count == 0)
                    return;

                DialogResult result = DialogResult.Cancel;
                if (MainListView.SelectedItems.Count == 1)
                {
                    string name = MainListView.SelectedItems[0].Text;
                    result = MessageBox.Show("Do you want to delete " + name + " ?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                }
                else
                {
                    result = MessageBox.Show("Do you want to delete " + MainListView.SelectedItems.Count + " item?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                }

                if (result == DialogResult.Yes)
                {
                    doDel();
                }

                return;
            }

            if (e.KeyCode == Keys.Enter)
            {
                this.Cursor = Cursors.WaitCursor;

                ListViewItem myItem = MainListView.SelectedItems[0];
                string nameFile = myItem.SubItems[0].Text;
                if (CheckFile(nameFile))
                {
                    try
                    {
                        Process.Start(currentPath + "\\" + nameFile);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    int index = 0;
                    foreach (TreeNode tmpNode in curNode.Nodes)
                        if (tmpNode.Text == myItem.Text)
                        {
                            index = tmpNode.Index;
                            break;
                        }

                    curNode = curNode.Nodes[index];

                    string sPath = curNode.FullPath.Replace("My Computer\\", "");
                    sPath.Replace("\\\\", "\\");

                    DirectoryInfo myDirInfo = new DirectoryInfo(sPath);
                    curDir = myDirInfo.GetDirectories();

                    currentPath = sPath;

                    ExpandTreeNode(curNode);

                    ShowDirectories();
                    ShowFiles(sPath);

                    curNode.Expand();

                    MainTreeView.SelectedNode = curNode;
                }
                this.Cursor = Cursors.Default;
            }
        }

        private void doDel()
        {
            foreach (ListViewItem item in MainListView.SelectedItems)
            {
                string name = item.SubItems[0].Text;
                if (CheckFile(name))
                {
                    DeleteFile(currentPath + "\\" + name);
                }
                else
                {
                    DeleteDirectory(currentPath + "\\" + name);
                }
            }

            doRefresh();
        }

        private bool CheckFile(string sFileName)
        {
            if (sFileName.Contains("."))
                return true;
            else
                return false;
        }

        private void DeleteFile(string path)
        {
            try
            {
                File.Delete(path);
            }
            catch
            {
                MessageBox.Show("không thể delete file này", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DeleteDirectory(string path)
        {
            path = path.Replace("\\\\", "\\");
            if (Directory.Exists(path))
            {
                DirectoryInfo curDir = new DirectoryInfo(path);
                DirectoryInfo[] allDirs = curDir.GetDirectories();
                FileInfo[] allFiles = curDir.GetFiles();
                foreach (DirectoryInfo myDirInfo in allDirs)
                    DeleteDirectory(path + "\\" + myDirInfo.Name);
                foreach (FileInfo myFileInfo in allFiles)
                    try
                    {
                        File.Delete(path + "\\" + myFileInfo.Name);
                    }
                    catch
                    {
                        MessageBox.Show("không thể delete " + myFileInfo.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                Directory.Delete(path);
            }
        }

        private void doRefresh()
        {
            // cho nay
            this.Cursor = Cursors.WaitCursor;
            string sPath = curNode.FullPath.Replace("My Computer\\", "");

            MainListView.Items.Clear();
            // truong hop la drive
            if (sPath.Length == 2)
            {
                sPath += "\\";
            }
            DirectoryInfo myDirInfo = new DirectoryInfo(sPath);
            curDir = myDirInfo.GetDirectories();
            ExpandTreeNode(curNode);
            ShowDirectories();
            ShowFiles(sPath);

            this.Cursor = Cursors.Default;
        }

        private void MainListView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (MainListView.SelectedItems.Count == 0)
                    return;

                DialogResult result = DialogResult.Cancel;
                if (MainListView.SelectedItems.Count == 1)
                {
                    string name = MainListView.SelectedItems[0].Text;
                    result = MessageBox.Show("bạn có muốn xóa " + name + " ?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                }
                else
                {
                    result = MessageBox.Show("bạn có muốn xóa " + MainListView.SelectedItems.Count + " item?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                }

                if (result == DialogResult.Yes)
                {
                    doDel();
                }

                return;
            }

            if (e.KeyCode == Keys.Enter)
            {
                this.Cursor = Cursors.WaitCursor;

                ListViewItem myItem = MainListView.SelectedItems[0];
                string nameFile = myItem.SubItems[0].Text;
                if (CheckFile(nameFile))
                {
                    try
                    {
                        Process.Start(currentPath + "\\" + nameFile);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    int index = 0;
                    foreach (TreeNode tmpNode in curNode.Nodes)
                        if (tmpNode.Text == myItem.Text)
                        {
                            index = tmpNode.Index;
                            break;
                        }

                    curNode = curNode.Nodes[index];

                    string sPath = curNode.FullPath.Replace("My Computer\\", "");
                    sPath.Replace("\\\\", "\\");

                    DirectoryInfo myDirInfo = new DirectoryInfo(sPath);
                    curDir = myDirInfo.GetDirectories();

                    currentPath = sPath;

                    ExpandTreeNode(curNode);

                    ShowDirectories();
                    ShowFiles(sPath);

                    curNode.Expand();

                    MainTreeView.SelectedNode = curNode;
                }
                this.Cursor = Cursors.Default;
            }
        }

        private void MainListView_MouseClick(object sender, MouseEventArgs e)
        {
            if (MainListView.SelectedItems.Count > 0)
            {
                ListViewItem myItem = MainListView.Items[MainListView.SelectedIndices[0]];

                string sPathFile = currentPath + MainListView.SelectedItems[0].SubItems[0].Text;
                labelStatus.Text = sPathFile;
            }
        }

        private void MainListView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Cursor = Cursors.WaitCursor;

                ListViewItem myItem = MainListView.SelectedItems[0];
                string nameFile = myItem.SubItems[0].Text;
                if (CheckFile(nameFile))
                {
                    try
                    {
                        Process.Start(currentPath + "\\" + nameFile);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    int index = 0;
                    foreach (TreeNode tmpNode in curNode.Nodes)
                        if (tmpNode.Text == myItem.Text)
                        {
                            index = tmpNode.Index;
                            break;
                        }

                    curNode = curNode.Nodes[index];

                    string sPath = curNode.FullPath.Replace("My Computer\\", "");
                    sPath.Replace("\\\\", "\\");

                    DirectoryInfo myDirInfo = new DirectoryInfo(sPath);
                    curDir = myDirInfo.GetDirectories();

                    currentPath = sPath;

                    ExpandTreeNode(curNode);

                    ShowDirectories();
                    ShowFiles(sPath);

                    curNode.Expand();

                    MainTreeView.SelectedNode = curNode;
                }
                this.Cursor = Cursors.Default;
            }
        }

        private void largeIconToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainListView.View = View.LargeIcon;
        }

        private void smallIconToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainListView.View = View.SmallIcon;
        }

        private void listToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainListView.View = View.List;
        }

        private void detailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainListView.View = View.Details;
        }

        private void showHiddenFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentPath != "My Computer")
                doRefresh();
        }

        private void showSystemFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentPath != "My Computer")
                doRefresh();
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            if (MainListView.SelectedItems.Count == 0)
                return;
            doCopy();
        }

        private void doCopy()
        {
            this.btnPaste.Enabled = true;

            foreach (ListViewItem item in MainListView.SelectedItems)
            {
                lstCopyFilePath.Add(currentPath + "\\" + item.SubItems[0].Text);
            }
            isCopy = true;
        }

        private void btnPaste_Click(object sender, EventArgs e)
        {
            if (currentPath != "My Computer" && currentPath != "")
                doPaste();
        }

        private void doPaste()
        {
            this.Cursor = Cursors.WaitCursor;
            foreach (string s in lstCopyFilePath)
            {
                if (isCopy)
                {
                    //copy file
                    if (CheckFile(s))
                    {
                        CopyFile(s, currentPath + "\\" + GetFileName(s));
                    }
                    else
                    {
                        CopyDirectory(s, currentPath);
                    }
                }
                else
                {
                    //cut file
                    if (CheckFile(s))
                    {
                        MoveFile(s, currentPath + "\\" + GetFileName(s));
                    }
                    else
                    {
                        MoveDirectory(s, currentPath);
                    }
                }
            }

            doRefresh();

            this.Cursor = Cursors.Default;
            this.btnPaste.Enabled = false;
        }

        private void CopyFile(string srcPath, string desPath)
        {
            srcPath = srcPath.Replace("\\\\", "\\");
            desPath = desPath.Replace("\\\\", "\\");
            if (File.Exists(srcPath))
            {
                if (File.Exists(desPath))
                {
                    string sFileName = GetFileName(desPath);
                    desPath = desPath.Insert(desPath.Length - sFileName.Length, "Copy of ");
                }

                File.Copy(srcPath, desPath);
            }
        }

        private string GetFileName(string filePath)
        {
            string[] arr = filePath.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
            if (arr != null && arr.Length > 0)
            {
                return arr[arr.Length - 1];
            }
            else
            {
                return string.Empty;
            }
        }

        private void CopyDirectory(string srcPath, string desPath)
        {
            srcPath = srcPath.Replace("\\\\", "\\");
            desPath = desPath.Replace("\\\\", "\\");

            if (Directory.Exists(srcPath))
            {
                if (!Directory.Exists(desPath))
                    Directory.CreateDirectory(desPath);

                DirectoryInfo curDir = new DirectoryInfo(srcPath);
                DirectoryInfo[] allDirs = curDir.GetDirectories();
                FileInfo[] allFiles = curDir.GetFiles();
                foreach (DirectoryInfo myDirInfo in allDirs)
                    CopyDirectory(srcPath + "\\" + myDirInfo.Name, desPath + "\\" + myDirInfo.Name);
                foreach (FileInfo myFileInfo in allFiles)
                    CopyFile(srcPath + "\\" + myFileInfo.Name, desPath + "\\" + myFileInfo.Name);
            }
        }

        private bool MoveFile(string srcPath, string desPath)
        {
            srcPath = srcPath.Replace("\\\\", "\\");
            desPath = desPath.Replace("\\\\", "\\");

            if (srcPath.Equals(desPath))
            {
                MessageBox.Show("Cannot move file, The source path and the destination path is the same", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (File.Exists(srcPath))
            {
                if (File.Exists(desPath))
                {
                    if (MessageBox.Show("The file " + desPath + " already exists. Do you want to overwrite it?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        File.Delete(desPath);

                        return true;
                    }
                }

                File.Copy(srcPath, desPath);

                File.Delete(srcPath);
            }
            return false;
        }

        private bool MoveDirectory(string srcPath, string desPath)
        {
            srcPath = srcPath.Replace("\\\\", "\\");
            desPath = desPath.Replace("\\\\", "\\");
            if (Directory.Exists(srcPath))
            {

                bool ok = true;
                if (Directory.Exists(desPath) == false) Directory.CreateDirectory(desPath);
                DirectoryInfo cdir = new DirectoryInfo(srcPath);
                DirectoryInfo[] dirs = cdir.GetDirectories();
                FileInfo[] files = cdir.GetFiles();
                foreach (DirectoryInfo dir in dirs)
                    if (MoveDirectory(srcPath + "\\" + dir.Name, desPath + "\\" + dir.Name) == false)
                        ok = false;
                foreach (FileInfo file in files)
                    if (MoveFile(srcPath + "\\" + file.Name, desPath + "\\" + file.Name) == false)
                        ok = false;
                if (ok)
                {
                    Directory.Delete(srcPath);
                    return true;
                }
            }
            return false;
        }

        private void btnCut_Click(object sender, EventArgs e)
        {
            if (MainListView.SelectedItems.Count == 0)
                return;
            doCut();
        }

        private void doCut()
        {
            foreach (ListViewItem item in MainListView.SelectedItems)
            {
                lstCopyFilePath.Add(currentPath + "\\" + item.SubItems[0].Text);
            }

            this.btnPaste.Enabled = true;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MainListView.SelectedItems.Count == 0)
                return;

            DialogResult result = DialogResult.Cancel;
            if (MainListView.SelectedItems.Count == 1)
            {
                string name = MainListView.SelectedItems[0].Text;
                result = MessageBox.Show("bạn có muốn xóa " + name + " ?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
            else
            {
                result = MessageBox.Show("bạn có muốn xóa " + MainListView.SelectedItems.Count + " item?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            }

            if (result == DialogResult.Yes)
            {
                doDel();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (currentPath != "My Computer")
                doRefresh();
        }

        private void toolStripMenuItemCopy_Click(object sender, EventArgs e)
        {
            if (MainListView.SelectedItems.Count == 0)
                return;

            toolStripMenuItemPaste.Enabled = true;

            doCopy();
        }

        private void toolStripMenuItemPaste_Click(object sender, EventArgs e)
        {
            if (currentPath != "My Computer" && currentPath != "")
                doPaste();

            toolStripMenuItemPaste.Enabled = false;
        }

        private void toolStripMenuItemCut_Click(object sender, EventArgs e)
        {
            if (MainListView.SelectedItems.Count == 0)
                return;

            toolStripMenuItemPaste.Enabled = true;

            doCut();
        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            if (MainListView.SelectedItems.Count == 0)
                return;

            DialogResult result;
            if (MainListView.SelectedItems.Count == 1)
            {
                string name = MainListView.SelectedItems[0].Text;
                result = MessageBox.Show("bạn có muốn xóa " + name + " ?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
            else
            {
                result = MessageBox.Show("bạn có muốn xóa " + MainListView.SelectedItems.Count + " item?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            }

            if (result == DialogResult.Yes)
            {
                doDel();
            }
        }

        private void signFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = string.Empty;

                if (MainListView.SelectedItems.Count == 0)
                {
                    MessageBox.Show("làm ơn chọn file để ký!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    filePath = currentPath + MainListView.SelectedItems[0].SubItems[0].Text;
                    if (CheckFile(filePath))
                    {
                        User user = Program.CurrentUser;
                        ConfirmPassFrm frm = new ConfirmPassFrm(user);
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            Stream inStream = new StreamReader(filePath).BaseStream;
                            Stream outStream = new StreamWriter(filePath + ".sig").BaseStream;
                            RSACryptoServiceProvider rsa = Program.CurrentUser.GetRSAKeyPair(true);
                            EncryptionProvider.Sign(inStream, outStream, rsa, Utility.HashAlgo);

                            doRefresh();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Làm ơn chọn file để ký!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void verifySignatureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                VerifyDigiSigFrm frm = new VerifyDigiSigFrm();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    string filePath = frm.FilePath;
                    string sigFilePath = frm.SigFilePath;

                    foreach (User u in Program.ListUser.Users)
                    {
                        Stream inStream = new StreamReader(filePath).BaseStream;
                        Stream signStream = new StreamReader(sigFilePath).BaseStream;
                        RSACryptoServiceProvider rsa = u.GetRSAKeyPair(false);
                        if (EncryptionProvider.Verify(inStream, signStream, rsa, Utility.HashAlgo))
                        {
                            MessageBox.Show("chữ ký đúng của " + u.ToString(), Utility.InformTitle);
                            return;
                        }
                    }
                    MessageBox.Show("chữ ký không đúng.", Utility.InformTitle);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void encryptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = string.Empty;

                if (MainListView.SelectedItems.Count == 0)
                {
                    MessageBox.Show("Làm ơn chọn file để mã hóa", Utility.ErrorTitle);
                    return;
                }
                else
                {
                    filePath = currentPath + MainListView.SelectedItems[0].SubItems[0].Text;
                    if (CheckFile(filePath))
                    {
                        User user = Program.CurrentUser;
                        Stream ins = new StreamReader(filePath).BaseStream;

                        if (MessageBox.Show("Bạn có muốn nén file này trước khi mã hóa?", Utility.InformTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                            == DialogResult.Yes)
                        {
                            filePath += ".gzip";
                            Stream compress = new StreamWriter(filePath, false).BaseStream;
                            Compressor.Compress(ins, compress);
                            ins = new StreamReader(filePath).BaseStream;
                        }
                        EncryptFrm encryptForm = new EncryptFrm();
                        if (encryptForm.ShowDialog(this) == DialogResult.OK)
                        {
                            byte[] key = EncryptionProvider.GenerateKeyBytes(encryptForm.EncryptionAlgorithm);
                            // encrypt key with receiver rsa public key
                            RSACryptoServiceProvider rsa = encryptForm.Receiver.GetRSAKeyPair(false);
                            Stream outs = new StreamWriter(filePath + ".enc", false).BaseStream;

                            try
                            {
                                EncryptionProvider.Encrypt(ins, outs,
                                    encryptForm.EncryptionAlgorithm,
                                    key,
                                    rsa,
                                    encryptForm.PaddingMode,
                                    encryptForm.CipherMode);

                                MessageBox.Show("Mã hóa thành công!.", Utility.InformTitle);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, Utility.ExceptionTitle);
                                return;
                            }

                        }
                    }
                    else
                    {
                        MessageBox.Show("Làm ơn chọn file, đừng chọn thư mục!", Utility.ErrorTitle);
                        return;
                    }
                }
                doRefresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utility.ExceptionTitle);
            }
        }

        private void decryptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = string.Empty;

                if (MainListView.SelectedItems.Count == 0)
                {
                    MessageBox.Show("Làm ơn chọn file để giải mã!", Utility.ErrorTitle);
                    return;
                }
                else
                {
                    filePath = currentPath + MainListView.SelectedItems[0].SubItems[0].Text;
                    if (CheckFile(filePath))
                    {
                        User user = Program.CurrentUser;
                        ConfirmPassFrm frm = new ConfirmPassFrm(user);
                        if (frm.ShowDialog(this) == DialogResult.OK)
                        {
                            Stream enc = new StreamReader(filePath).BaseStream;
                            // strip extension
                            string outputPath = filePath.Remove(filePath.LastIndexOf('.'));
                            bool isCompress = false;
                            // kiểm tra nếu file đã nén
                            if (outputPath.Substring(outputPath.Length - 4).Equals("gzip"))
                            {
                                isCompress = true;
                            }
                            Stream dec = new StreamWriter(outputPath).BaseStream;

                            RSACryptoServiceProvider rsa = Program.CurrentUser.GetRSAKeyPair(true);
                            try
                            {
                                EncryptionProvider.Decrypt(enc, dec, rsa);
                                // giải nén file
                                if (isCompress)
                                {
                                    Stream compress = new StreamReader(outputPath).BaseStream;
                                    string finalPath = outputPath.Remove(outputPath.LastIndexOf('.'));
                                    Stream decompress = new StreamWriter(finalPath, false).BaseStream;
                                    Compressor.Decompress(compress, decompress);
                                }
                                MessageBox.Show("Giải mã thành công!.", Utility.InformTitle);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, Utility.ExceptionTitle);
                                return;
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Làm ơn chọn file, đừng chọn thư mục!.", Utility.ErrorTitle);
                        return;
                    }
                }
                doRefresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utility.ExceptionTitle);
            }
        }

        private void zipFIleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = string.Empty;

                if (MainListView.SelectedItems.Count == 0)
                {
                    MessageBox.Show("Làm ơn chọn file để nén!.", Utility.ErrorTitle);
                    return;
                }
                else
                {
                    filePath = currentPath + MainListView.SelectedItems[0].SubItems[0].Text;
                    ZipFile zip = new ZipFile();

                    if (CheckFile(filePath))
                    {
                        zip.AddFile(filePath);
                        string zipFile = filePath.Remove(filePath.LastIndexOf('.')) + ".zip";
                        zip.Save(zipFile);
                    }
                    else
                    {
                        zip.AddDirectory(filePath);
                        zip.Save(filePath + ".zip");
                    }

                    doRefresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utility.ExceptionTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void unZipFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = string.Empty;

                if (MainListView.SelectedItems.Count == 0)
                {
                    MessageBox.Show("Làm ơn chọn file để giải nén!.", Utility.ErrorTitle);
                    return;
                }
                else
                {
                    filePath = currentPath + MainListView.SelectedItems[0].SubItems[0].Text;

                    if (!filePath.Contains(".zip"))
                    {
                        MessageBox.Show("Không thể giải nén!. " + filePath, Utility.ErrorTitle);
                        return;
                    }
                    else
                    {
                        string zipToUnpack = filePath;
                        string unpackDirectory = filePath.Remove(filePath.LastIndexOf('.'));

                        ZipFile zip1 = ZipFile.Read(zipToUnpack);

                        foreach (ZipEntry entry in zip1)
                        {
                            entry.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
                        }

                        doRefresh();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Utility.ExceptionTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
